package com.wennn.top.core.exception;

import com.wennn.top.common.vo.IResult;
import com.wennn.top.core.util.CoreConst;
import com.wennn.top.security.exception.TokenException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Optional;

/**
 * @description:
 * @author: wennn
 * @date: 5/24/20
 */
@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {


    @ExceptionHandler(TokenException.class)
    @ResponseBody
    public IResult token(TokenException e){
        dolog(e);
        return IResult.fail(e.getMessage());
    }

    @ExceptionHandler(RuntimeException.class)
    @ResponseBody
    public IResult busiError(RuntimeException e){
        dolog(e);
        return IResult.fail(CoreConst.ERROR,e.getMessage());
    }

    @ExceptionHandler(WBusiException.class)
    @ResponseBody
    public IResult busiError(WBaseException e){
        dolog(e);
        return Optional.ofNullable(e.getResult()).orElseGet(()->IResult.fail(CoreConst.FAIL,"业务出错"));
    }

    /*
     * 日志记录
     * @param e
     */
    @Async
    private void dolog(RuntimeException e) {
        if(e instanceof WBaseException){
            log.error("出错结果:{}",((WBaseException)e).getResult());
        }
        log.error("出错详情:{}",e.getMessage());
        log.error("出错类型Throw:{}",e);
    }


}
